/**
 * AI Model Face & Hair Detail Fix Template Test
 * 
 * This example demonstrates how to use the built-in AI model face and hair
 * detail enhancement template for professional photo enhancement.
 */

import { ComfyUIClient, aiModelFaceHairFixTemplate } from '../src';

async function testAiModelFaceHairFix() {
  console.log('🚀 Starting AI Model Face & Hair Detail Fix Test');
  
  // Initialize client
  const client = new ComfyUIClient({
    baseUrl: 'http://192.168.0.193:8188'
  });

  try {
    // Connect to ComfyUI server
    console.log('📡 Connecting to ComfyUI server...');
    await client.connect();
    console.log('✅ Connected successfully!');

    // Register the built-in template
    console.log('📝 Registering AI Model Face & Hair Fix template...');
    client.templates.registerFromData(aiModelFaceHairFixTemplate);
    console.log('✅ Template registered!');

    // Get the registered template
    const template = client.templates.getById(aiModelFaceHairFixTemplate.metadata.id);
    if (!template) {
      throw new Error('Failed to register template');
    }

    console.log(`📋 Template ID: ${template.id}`);
    console.log(`📋 Template Name: ${template.name}`);
    console.log(`📋 Template Description: ${template.description}`);

    // Test template parameters
    console.log('\n🔍 Template Parameters:');
    const parameterNames = Object.keys(template.parameters);
    parameterNames.forEach(name => {
      const schema = template.getParameterSchema(name);
      console.log(`  - ${name}: ${schema?.type} (${schema?.description})`);
    });

    // Execute the template with test parameters
    console.log('\n🎨 Executing AI Model Face & Hair Enhancement...');
    const result = await client.executeTemplate(template, {
      input_image: '20250806-190606.jpg',
      face_prompt: 'beautiful woman, perfect skin, detailed facial features',
      face_denoise: '0.25'
    }, {
      callbacks: {
        onProgress: (progress) => {
          const percentage = Math.round((progress.progress / progress.max) * 100);
          console.log(`⏳ Progress: ${percentage}% (${progress.progress}/${progress.max}) - Node: ${progress.nodeId}`);
        },
        onExecuting: (nodeId) => {
          console.log(`🔄 Executing node: ${nodeId}`);
        },
        onExecuted: (result) => {
          console.log(`✅ Node executed: ${JSON.stringify(result.outputs)}`);
        },
        onError: (error) => {
          console.error(`❌ Execution error: ${error.message}`);
        }
      },
      timeout: 120000 // 2 minutes timeout for complex workflow
    });

    if (result.success) {
      console.log('\n🎉 AI Model Enhancement completed successfully!');
      console.log(`📊 Execution time: ${result.executionTime}ms`);
      console.log(`🆔 Prompt ID: ${result.promptId}`);
      
      if (result.outputs) {
        console.log('📁 Outputs:', JSON.stringify(result.outputs, null, 2));
        
        // Convert outputs to HTTP URLs
        const imageUrls = client.outputsToUrls(result.outputs);
        console.log('🖼️  Enhanced Image URLs:', imageUrls);
      }
    } else {
      console.error('❌ AI Model Enhancement failed:', result.error?.message);
    }

  } catch (error) {
    console.error('💥 Error:', error);
  } finally {
    // Disconnect
    console.log('\n🔌 Disconnecting...');
    await client.disconnect();
    console.log('👋 Disconnected!');
  }
}

// Template validation test
async function validateTemplate() {
  console.log('\n🔍 Template Validation Test');

  const client = new ComfyUIClient({
    baseUrl: 'http://192.168.0.193:8188'
  });

  try {
    // Register template and get it
    client.templates.registerFromData(aiModelFaceHairFixTemplate);
    const template = client.templates.getById(aiModelFaceHairFixTemplate.metadata.id);

    if (!template) {
      throw new Error('Failed to register template for validation test');
    }

    // Test parameter validation
    console.log('📝 Testing parameter validation...');

    // Valid parameters
    const validParams = {
      input_image: 'test.jpg',
      face_prompt: 'beautiful face',
      face_denoise: '0.3'
    };

    const validationResult = template.validate(validParams);
    console.log('✅ Valid parameters test:', validationResult.valid ? 'PASSED' : 'FAILED');

    if (!validationResult.valid) {
      console.log('❌ Validation errors:', validationResult.errors);
    }

    // Test invalid parameters
    const invalidParams = {
      input_image: '', // Empty required field
      face_prompt: 'test',
      face_denoise: '2.0' // Out of range (should be string anyway)
    };

    const invalidValidation = template.validate(invalidParams);
    console.log('🚫 Invalid parameters test:', !invalidValidation.valid ? 'PASSED' : 'FAILED');

    if (!invalidValidation.valid) {
      console.log('📋 Expected validation errors:', invalidValidation.errors.map(e => e.message));
    }

  } catch (error) {
    console.error('💥 Validation test error:', error);
  }
}

// Run tests
async function runTests() {
  try {
    await validateTemplate();
    await testAiModelFaceHairFix();
  } catch (error) {
    console.error('💥 Test suite error:', error);
    process.exit(1);
  }
}

// Execute if run directly
if (require.main === module) {
  runTests();
}

export { testAiModelFaceHairFix, validateTemplate };
